package c.x.jy.api.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.h2.util.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import c.x.jy.common.exception.RRException;
import c.x.jy.common.utils.R;
import lombok.extern.slf4j.Slf4j;

 @Slf4j
@Component
public class ExceptionResolver implements HandlerExceptionResolver {

     
  
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @Nullable Object o, Exception e) {
        httpServletResponse.setHeader("Content-type", "text/html;charset=UTF-8");
        PrintWriter writer = null;
        try {
          R r;
            if (e instanceof UnknownAccountException){
               r= R.error( 1, "用户名不存在");
            }else if (e instanceof LockedAccountException) {
                r= R.error( 1, "用户异常，被锁定");
            }else if (e instanceof AuthenticationException) {
                r= R.error( 1, "用户名或密码错误");
            }else if(e instanceof AuthorizationException){
                r= R.error( 1, "没有权限访问");
            }else if(e instanceof RRException){
                if (!StringUtils.isNullOrEmpty(e.getMessage())) {
                    r= R.error( ((RRException) e).getCode(), e.getMessage());
                }else{
                    r= R.error( 1, "未知错误!");
                }
            } else {
            	r= R.error( 1,"系统发生了一个错误，请稍后再试!");
            //    logger.error("未知错误",e);
            }
         //   e.printStackTrace();
         writer = httpServletResponse.getWriter();
         writer.print(JSON.toJSONString(r));
          //  writer.flush();
           // httpServletResponse.getWriter().close();
        } catch (Exception e1) {
        	log.debug(e.getMessage());
            e1.printStackTrace();
        }finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }
        return null;
    }
}
